﻿#include "player.h"

bool Player::init()
{
    m_pSound=nullptr;
    m_pChannel=nullptr;
    state=Stop;

    result1=FMOD::System_Create(&m_pSystem);
    result2=m_pSystem->init(64,FMOD_INIT_NORMAL,0);

    if(result1 !=FMOD_OK || result2 !=FMOD_OK)
        return false;
    else
        return true;
}

void Player::close()
{
    if (m_pChannel != nullptr)
        m_pChannel->stop();
    if (m_pSound != nullptr)
        m_pSound->release();
    if (m_pSystem != nullptr)
    {
        m_pSystem->close();
        m_pSystem->release();
    }
}

bool Player::play(const QString &fileName)
{
    if(m_pChannel !=nullptr)
        m_pChannel->stop();
    if(m_pSound !=nullptr)
        m_pSound->release();

    QByteArray byte=fileName.toLocal8Bit();
    std::string name=byte.toStdString();
    result1=m_pSystem->createStream(name.c_str(),FMOD_HARDWARE | FMOD_LOOP_NORMAL,0,&m_pSound);
    result2=m_pSystem->playSound(FMOD_CHANNEL_FREE,m_pSound,false,&m_pChannel);

    if(result1 != FMOD_OK || result2 != FMOD_OK)
        return false;
    else
    {
        state=Play;
        return true;
    }
}

bool Player::isPlaying()
{
    if(state == Play)
        return true;
    else
        return false;
}

void Player::stop()
{
    if(m_pChannel !=nullptr)
        m_pChannel->stop();
    state=Stop;
}

void Player::pause()
{
    if(m_pChannel !=nullptr)
        m_pChannel->setPaused(true);
    state=Pause;
}

void Player::resume()
{
    if(m_pChannel !=nullptr)
        m_pChannel->setPaused(false);
    state=Play;
}

void Player::detectState()
{
    if(state==Play)
        pause();
    else if(state==Pause)
        resume();
}
